"use client";

import { useEffect, useState } from "react";
import { getPersonas, PersonaSummary } from "@/lib/api/persona";
import { useAuth } from "@/lib/auth/context";

export function usePersonas(options?: { enabled?: boolean }) {
  const { loading: authLoading, user, refresh } = useAuth();
  const [data, setData] = useState<PersonaSummary[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const enabled = options?.enabled ?? true;

  useEffect(() => {
    if (!enabled || authLoading || !user) return;
    const controller = new AbortController();
    setLoading(true);
    (async () => {
      try {
        const res = await getPersonas(controller.signal);
        setData(res);
        setError(null);
      } catch (e: any) {
        if (e?.status === 401) {
          try {
            await refresh();
            const res2 = await getPersonas(controller.signal);
            setData(res2);
            setError(null);
          } catch (e2: any) {
            setError(e2?.message ?? "Loading failed");
          }
        } else {
          setError(e?.message ?? "Loading failed");
        }
      } finally {
        setLoading(false);
      }
    })();
    return () => controller.abort();
  }, [enabled, authLoading, user, refresh]);

  return { data: data ?? [], loading, error };
}